package com.yesjpt.util;

import java.security.Security;
//import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.alibaba.fastjson2.JSONObject;
import com.yesjpt.domain.MailAuthenticator;

/**
 * javaMail的邮件工具类
 * @author 
 *
 */
public class MailUtil {
	public static void main(String[] args) throws Exception {
//	    发送SSL认证邮件
        System.out.println(sendSSL("293440@qq.com", "太好了", "实在是太好了"));
		//System.out.println(send("293440@qq.com", "大家好", "今天的天气巴适" + new Date()));
	}

    /**
     * 使用加密的方式,利用465端口进行传输邮件,开启ssl
     * @param to    为收件人邮箱
     * @param subject 主题
     * @param content 内容
     */
	@SuppressWarnings("restriction")
	public static JSONObject sendSSL(String to, String subject, String content) {
    	L.info(new Throwable().getStackTrace()[0] + ", to = " + to + ", subject = " + subject + ", content = " + content);
        try {
        	//加密协议设置
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            //设置邮件会话参数
            Properties props = new Properties();
            //邮箱的发送服务器地址
            props.setProperty("mail.smtp.host", "smtp.sina.com");
            props.put("mail.smtp.auth", "true");
            final String username = "chenjianbo@sina.com";
            final String password = "123456";
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            //只处理SSL的连接, 对于非SSL的连接不做处理
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            //邮箱发送服务器端口,这里设置为465端口
            props.setProperty("mail.smtp.port", "465");
            props.setProperty("mail.smtp.socketFactory.port", "465");
            //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
            Session session = Session.getInstance(
            		props, 
            		new Authenticator() {
            			protected PasswordAuthentication getPasswordAuthentication() {
            				return new PasswordAuthentication(username, password);
            			}
            		}
            );
            //通过会话,得到一个邮件,用于发送
            Message msg = new MimeMessage(session);
            //设置发件人
            msg.setFrom(new InternetAddress("chenjianbo@sina.com", "西南交通大学"));
            //设置收件人,to为收件人,cc为抄送,bcc为密送
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, false));
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));
            msg.setSubject(subject);
            //设置邮件消息
            msg.setText(content);
            //设置发送的日期
            msg.setSentDate(new Date());
            System.out.println("开始发送");
            //调用Transport的send方法去发送邮件
            Transport.send(msg);
            System.out.println("发完了");
            return ContextUtil.ret(true, "邮件发送成功，地址为：" + to);
        } catch (Exception e) {
            e.printStackTrace();
            return ContextUtil.ret(false, "邮件发送异常，地址为：" + to);
        }
    }
	public static JSONObject send(String to, String subject, String content){
    	L.info(new Throwable().getStackTrace()[0] + ", to = " + to + ", subject = " + subject + ", content = " + content);
    	//认证参数
        Properties prop = new Properties(); 
        Authenticator auth = new MailAuthenticator("jbchen@swjtu.edu.cn", "123456");
        prop.put("mail.smtp.host", "mail.swjtu.edu.cn");
        prop.put("mail.smtp.auth", "true");//代表向SMTP服务器认证
        
        //认证
        Session session = Session.getInstance(prop, auth);
        
        //生成邮件
        Message message = new MimeMessage(session);   
        try{   
            message.setSubject(subject);
            message.setHeader("Header", subject); 
            message.setSentDate(new Date());
            Address from = new InternetAddress("jbchen@swjtu.edu.cn", "好人陈剑波");//让接收方回复到293440@qq.com
            message.setFrom(from);
            Address toAddress = new InternetAddress(to); 
            message.setRecipient(Message.RecipientType.TO, toAddress);
            message.setContent("Content", content); 
            message.setText(content); 
            message.saveChanges();
            
            //发送邮件
            System.out.println("邮件发送中");
            Transport.send(message);
            System.out.println("邮件发送完毕");
        	//保存返回结果
    		JSONObject o = new JSONObject();
    		o.put("success", true);
            o.put("message", "邮件成功发送到：" + to);
            return o;
        } catch (Exception e){   
        	L.error("邮件发送异常：" + e); 
            e.printStackTrace();
            return ContextUtil.ret(false, "邮件发送失败：" + to + "，错误信息：" + e);
        }   
    }
}




















